package cee

import (
	"errors"
	"net/http"
)

type Cee struct {
	routers *router
}

func New() *Cee {
	return &Cee{routers: newRouter()}
}

func (c *Cee) Run(addr string) error {
	return http.ListenAndServe(addr, c)
}

func (c *Cee) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	cont := newContext(w, r)

	if cont.Path == "/favicon.ico" {
		return
	}

	n, params := c.routers.getRoute(cont.Method, cont.Path)

	if n != nil {
		key := r.Method + "-" + n.pattern
		cont.Params = params
		handFunc := c.routers.handlers[key]
		handFunc(cont)
	} else {
		cont.WriteMsg(cont.Path + "路径找不到")
	}

}

func (c *Cee) AddRoute(method string, patter string, hand HandleFunc) {
	c.routers.addRoute(method, patter, hand)
}
func (c *Cee) Pin() {
	panic(errors.New("测试报错"))
}
